<template>
  <div class="breadcrumb">
    <!-- 导航栏部分 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- 默认样式紧挨着，这里的el-breadcrumb设置在全局样式文件 global.css中 -->
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片主体区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="30" class="mianbaoxie">
        <!-- :gutter="10"设置内部el-col之间的边距 -->
        <el-col :span="8">
          <!-- clearable ：多个可一键清空的小图标     @clear：点击一键清空后触发的事件-->
          <el-input
            placeholder="请输入内容"
            v-model="userparams.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4"
          ><el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          ></el-col
        >
        <!-- 添加用户的消息框 -->
        <!-- close：dialog表单关闭事件 -->
        <el-dialog
          title="添加用户"
          :visible.sync="addDialogVisible"
          width="40%"
          :before-close="beforeClose"
          @close="addDialogClosed"
        >
          <!-- ref：表单提交的对象名   rules：数据规则     model：数据对象，用于保存以便其他功能方法使用 -->
          <el-form
            :model="addUserForm"
            :rules="userRules"
            ref="addUserFormRef"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addUserForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="addUserForm.password"
                type="password"
              ></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addUserForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="addUserForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 修改用户的消息框 -->
        <!-- close：dialog表单关闭事件 -->
        <el-dialog
          title="修改用户"
          :visible.sync="editDialogVisible"
          width="40%"
          :before-close="beforeClose"
          @close="editDialogClose"
        >
          <!-- ref：表单提交的对象名   rules：数据规则     model：数据对象，用于保存以便其他功能方法使用 -->
          <el-form
            :model="editUserForm"
            :rules="userRules"
            ref="editUserFormRef"
            label-width="100px"
            class="demo-ruleForm"
            ><!-- el-form 的 :model属性值必须对应下面各个分标签的值 -->
            <el-form-item label="用户名">
              <el-input v-model="editUserForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editUserForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="editUserForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUser">确 定</el-button>
          </span>
        </el-dialog>
      </el-row>
      <!-- 信息展示部分 -->
      <el-table :data="userList" border stripe>
        <!-- border：显示边框   stripe：隔行变色 -->
        <el-table-column type="index" lable="#"></el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <!-- 通过 template来定义scope，通过其可以获取 row当前行信息，然后.mg_state就是用户状态的参数，设置到 switch 上就能显示状态了 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeState(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- size设置按钮大小 -->
          <!-- 通过 template来定义scope，通过其可以获取 row当前行信息，然后.mg_state就是用户状态的参数，设置到 switch 上就能显示状态了 -->
          <template slot-scope="scope">
            <el-button
              class="el-icon-edit-outline"
              type="primary"
              size="mini"
              @click="editUserDialog(scope.row)"
            ></el-button>
            <el-button
              class="el-icon-delete-solid"
              type="danger"
              size="mini"
              @click="deleteUserById(scope.row)"
            ></el-button>
            <!-- enterable 鼠标进入提示文字后文字会消失， placement 设置提示位置 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="设置角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                class="el-icon-setting"
                type="info"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页部分 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userparams.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="userparams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 分配权限的消息框 -->
    <el-dialog
      title="设置角色"
      :visible.sync="roleDialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <div>
        <p>当前的用户：{{ currentUserInfo.username }}</p>
        <p>当前的角色：{{ currentUserInfo.role_name }}</p>
        <p>
          分配新角色：<el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="commitRole()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      /* 用户信息列表 */
      userList: [],
      /* 发送请求的参数 */
      userparams: {
        // 搜索栏搜索的用户名关键字
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      /* 编辑用户的信息集合 */
      editUserForm: {},
      /* 总记录 */
      total: 0,
      // 添加框可见参数
      addDialogVisible: false,
      // 编辑框可见参数
      editDialogVisible: false,
      // 设置角色框可见参数
      roleDialogVisible: false,
      // 添加用户输入框的参数
      addUserForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      userRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 5,
            message: "长度在 3 到 5 个字符",
            trigger: "change",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "change",
          },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          {
            validator: function (rule, value, callback) {
              if (
                /^\w{1,64}@[a-z0-9\-]{1,256}(\.[a-z]{2,6}){1,2}$/i.test(
                  value
                ) == false
              ) {
                callback(new Error("邮箱格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机号码",
            trigger: "blur",
          },
          {
            validator: function (rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false) {
                callback(new Error("手机号格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      // 当前行用户信息。多个键值对，所以用集合｛｝
      currentUserInfo: {},
      // 角色列表
      rolesList: [],
      /* select 选中的值 */
      selectRoleId: '',
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.userparams,
      });
      if (res.meta.status != 200) return this.$messgae.error(res.meta.msg);
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // 改变页码
    handleSizeChange(newSize) {
      this.userparams.pagesize = newSize;
      this.getUserList();
    },
    // 改变页数
    handleCurrentChange(newPage) {
      this.userparams.pagenum = newPage;
      this.getUserList();
    },
    // 改变用户状态
    async changeState(scopeRow) {
      const { data: res } = await this.$http.put(
        `users/${scopeRow.id}/state/${scopeRow.mg_state}`
      );
      if (res.meta.status != 200) {
        scopeRow.mg_state = !scopeRow.mg_state;
        return this.$message.error("用户状态更新失败！");
      }
      this.$message.success("用户状态更新成功！");
    },
    //关闭新增、编辑用户dialog框的提示方法
    beforeClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    // 添加用户框关闭触发事件，重置表单，防止上次的错误信息在这次打开时出现
    addDialogClosed() {
      this.$refs.addUserFormRef.resetFields();
    },
    editDialogClose() {
      this.$refs.editUserFormRef.resetFields();
    },
    // 提交用户
    addUser() {
      this.$refs.addUserFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("users", this.addUserForm);
        if (res.meta.status !== 201)
          return this.$message.error("用户添加失败！");
        this.$message.success("用户添加成功!");
        this.addDialogVisible = false; 
        this.getUserList();
      });
    },
    // 展示编辑框
    async editUserDialog(scopeRow) {
      const { data: res } = await this.$http.get(
        `users/${scopeRow.id}`,
        this.addUserForm
      );
      if (res.meta.status !== 200)
        return this.$message.error("查询用户时失败！");
      this.editUserForm = res.data;
      this.editDialogVisible = true;
    },
    // 修改用户
    editUser() {
      this.$refs.editUserFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `users/${this.editUserForm.id}`,
          {
            email: this.editUserForm.email,
            mobile: this.editUserForm.mobile,
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error("用户修改失败！");
        this.$message.success("用户修改成功!");
        this.editDialogVisible = false;
        this.getUserList();
      });
    },
    // 删除用户
    async deleteUserById(scopeRow) {
      const confirmResult = await this.$confirm(
        "此操作将删除用户，是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err); /* 如果有异常就抛出 */
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete(`users/${scopeRow.id}`);
      if (res.meta.status != 200) {
        this.$message.error("用户删除失败！");
      }
      this.$message.success("用户删除成功！");
      this.getUserList();
    },
    // 点击设置角色触发
    async setRole(scope) {
      this.currentUserInfo = scope;
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status != 200) {
        this.$message.error("权限列表获取失败！");
      }
      this.rolesList = res.data;
      this.selectRoleId = scope.role_name;
      this.roleDialogVisible = true;
    },
    // 关闭消息框前提醒
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    // 编辑权限提交
    async commitRole(){
      const {data:res} = await this.$http.put(`users/${this.currentUserInfo.id}/role`,
      {
        rid:this.selectRoleId
      });
      if (res.meta.status != 200) {
        this.$message.error("角色分配失败！");
      }
      this.getUserList();
      this.roleDialogVisible = false;
    }
  },
};
</script>

<style lang="less" scoped>
</style>
